<template>
  <div>
    <div :class="['blog-details-content', loading ? 'addHeight' : '']">
      <div v-if="loading" class="loading-panel">
        <i class="el-icon-loading"></i>
      </div>
      <h1>{{ markdown.title }}</h1>
      <div class="content-mes">
        <span><icon-svg class="icon" name="user"></icon-svg>{{ markdown.author }}</span>
        <el-divider direction="vertical"></el-divider>
        <span
          ><icon-svg class="icon" name="columsManage"></icon-svg
          >{{ markdown.dynamicColumn.length ? markdown.dynamicColumn.join('、') : '暂无专栏' }}</span
        >
        <el-divider direction="vertical"></el-divider>
        <span
          ><icon-svg class="icon" name="time"></icon-svg
          >{{ markdown.createdAt ? $utils.formatDateTimeYMD(markdown.createdAt) : '' }}</span
        >
        <el-divider direction="vertical"></el-divider>
        <span><icon-svg class="icon" name="views"></icon-svg>{{ markdown.views }}</span>
      </div>
      <div class="line"></div>
      <div class="blog-details-blog" ref="content">{{ loading ? '' : markdown.contentEditor }}</div>
      <div class="btn-wrapper">
        <el-button class="btn" @click="clickDrink">
          <icon-svg name="coffee"></icon-svg>
          <span>请我喝杯咖啡</span>
        </el-button>
      </div>
      <el-divider></el-divider>
      <div class="clearfix">
        <div class="pre" v-if="preArticle">
          <span class="pre-page">上一篇</span>
          <span class="pre-blog-title" @click="goArticleDetails(preArticle.id)">{{ preArticle.title }}</span>
        </div>
        <div class="next" v-if="nextArticle">
          <span class="next-page">下一篇</span>
          <span class="next-blog-title" @click="goArticleDetails(nextArticle.id)">{{ nextArticle.title }}</span>
        </div>
      </div>
    </div>
    <div class="relation-item">
      <relation-item />
    </div>
  </div>
</template>

<script>
// import Vditor from 'vditor'
import throttle from 'lodash/throttle'
import relationItem from './details-relation-item.vue'
import highlightCode from '@/plugins/vditor-highlight.js'

export default {
  components: {
    relationItem
  },
  created() {
    this.articleId = this.$route.params.id
    // 根据id请求数据
    this.getData()
  },
  updated() {
    highlightCode()
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.myThrottle, false)
  },
  beforeRouteUpdate(to, from, next) {
    this.articleId = to.params.id
    // 根据id请求数据
    this.getData()
    next()
  },
  data() {
    return {
      loading: true,
      markdown: {
        author: '蜡笔小新',
        title: '',
        contentEditor: '',
        dynamicColumn: [],
        views: '',
        createdAt: ''
      },
      toc: [],
      headingElements: [],
      preArticle: {},
      nextArticle: {}
    }
  },
  methods: {
    goArticleDetails(id) {
      this.$router.push({ name: 'blog-details', params: { id } })
    },
    renderBlog() {
      this.$nextTick(() => {
        this.$vditor.preview(this.$refs.content, this.markdown.contentEditor, {
          hljs: {
            enable: true,
            style: 'native',
            lineNumber: true
          },
          after: () => {
            this.handleCatalog()
            this.loading = false
          }
        })
        highlightCode()
      })
    },
    getData() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(`/article/${this.articleId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.markdown = Object.assign({}, this.markdown, data.data.curArticle)
          this.nextArticle = data.data.nextArticle
          this.preArticle = data.data.preArticle
          this.renderBlog()
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    clickDrink() {
      this.$message({
        message: '谢谢啦🌸',
        type: 'success'
      })
    },
    myThrottle() {
      throttle(this.scrollHandle, 200)()
    },
    scrollHandle() {
      const scrollTop = window.scrollY
      this.toc = []
      this.headingElements.forEach((item) => {
        this.toc.push({
          id: item.id,
          offsetTop: item.offsetTop
        })
      })

      const currentElement = document.querySelector('.vditor-outline__item--current')
      for (let i = 0, iMax = this.toc.length; i < iMax; i++) {
        if (scrollTop < this.toc[i].offsetTop + 250) {
          if (currentElement) {
            currentElement.classList.remove('vditor-outline__item--current')
          }
          const targetDom = document.querySelector('span[data-target-id="' + this.toc[i].id + '"]')
          targetDom && targetDom.classList.add('vditor-outline__item--current')
          break
        }
      }
    },
    handleCatalog() {
      Array.from(this.$refs.content.children).forEach((item) => {
        if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
          this.headingElements.push(item)
        }
      })

      window.removeEventListener('scroll', this.myThrottle, false)
      window.addEventListener('scroll', this.myThrottle, false)

      // 获取目录div
      setTimeout(() => {
        const outlineElement =
          this.$parent.$children[0].$refs['outlineElement'] || this.$parent.$children[1].$refs['outlineElement']
        const outlineElementBox =
          this.$parent.$children[0].$refs['outlineElementBox'] || this.$parent.$children[1].$refs['outlineElementBox']
        // dom结构不同，位置就变化了。
        // // 第二次 0 下的 0
        // // 第一次 1 下的 0

        this.$vditor.outlineRender(this.$refs.content, outlineElement)
        if (outlineElement.innerText.trim() !== '') {
          outlineElementBox.style.display = 'block'
          outlineElement.style.display = 'block'
        } else {
          outlineElementBox.style.display = 'none'
        }
      }, 0)
    }
  }
}
</script>

<style lang="scss">
.blog-details-content {
  // 这个定位，为了使点击目录定位距离正确
  position: relative;
  z-index: 777;
  border-radius: 10px;
  padding: 20px;
  background: #fff;
  &.addHeight {
    height: 100%;
    min-height: 800px;
  }

  .loading-panel {
    position: absolute;
    display: flex;
    justify-content: center;
    padding-top: 300px;
    z-index: 1;
    width: 853px;
    height: calc(100% - 320px);
    background: #fff;
    font-size: 40px;
    color: $theme-blue;
    .el-icon-loading {
      height: 40px;
    }
  }
  .el-loading-mask {
    background-color: #fff;
  }

  & > h1 {
    font-size: 30px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .content-mes {
    margin: 25px 0;
    color: #999;
    font-size: 14px;
    > span {
      margin: 0 10px;
    }

    .icon {
      margin-right: 5px;
    }
  }

  .line {
    height: 1px;
    width: 100px;
    background: rgb(231, 231, 231);
  }

  .btn-wrapper {
    text-align: center;
    .btn {
      margin: 50px 0 10px;
    }
  }

  .pre {
    float: left;
    span {
      display: block;
    }
    .pre-page {
      color: #aaa;
      font-size: 12px;
      margin-bottom: 5px;
    }
    .pre-blog-title {
      width: 200px;
      color: #888;
      font-size: 14px;
      cursor: pointer;

      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &:hover {
        color: $theme-blue;
      }
    }
  }
  .next {
    float: right;
    text-align: end;
    span {
      display: block;
    }
    .next-page {
      color: #aaa;
      font-size: 12px;
      margin-bottom: 5px;
    }
    .next-blog-title {
      width: 200px;
      color: #888;
      font-size: 14px;
      cursor: pointer;

      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &:hover {
        color: $theme-blue;
      }
    }
  }
}
.relation-item {
  margin-top: 20px;
}
</style>
